import M from '../../../../common/typeMutations'
import A from '../../../../common/typeActions'
import L from '../../../../common/localStore'
import {action, mutation} from '../../../../common/quantity'
import crypto from 'crypto'
import process from 'child_process'
import moment from 'moment'
import axios from 'axios'

const skin = require('../../../../config/skin')
const state = {
  loading: false, // 是否显示等待界面
  loadingText: '', // 显示等待页面时文字提示
  isMaxWindow: false, // 窗口是否最大化
  currPage: 1, // 当前页面 1、主页，2、出庭预案页
  isSync: true, // 是否同步授权信息
  // 系统是否注册
  isRegisted: false,
  // 试用期限
  expireDays: 0,
  // 试用次数
  delayTimes: 0,
  usedDays: 0,
  usedTimes: 0,
  isExtensionUse: false,
  regInfo: null,
  // 机器码
  machineCode: '',
  // 序列号
  serialNo: '',
  setupInfo: {
    // 服务器IP
    serverIp: '',
    // 更新地址IP
    updateIp: ''
  },
  fullScreen: false
}

const mutations = {

  [mutation.container.setCurrPage] (state, data) {
    state.currPage = data
  },
  [mutation.container.fullScreen] (state, data) {
    state.fullScreen = !state.fullScreen
  },

  SET_LOADINGCASE (state, arg = {}) {
    state.loading = arg.loading
    state.loadingText = arg.loadingText || '请稍候...'
  },
  SET_WINDOWSTATUS (state, arg) {
    if (arg !== undefined) {
      state.isMaxWindow = arg
    } else {
      state.isMaxWindow = !state.isMaxWindow
    }
  },
  // //服务器地址IP配置
  // [M.CONTAINER.GET_SETUP_INFO](state, payload) {
  //   state.setupInfo.serverIp = payload.serverIp;
  //   state.setupInfo.updateIp = payload.updateIp;
  // },

  // 初始化容器
  [M.CONTAINER.initSetting] (state, obj) {
    state.isRegisted = obj.isRegisted ? true : false
    state.isSync = obj.isSync ? true : false
    state.delayTimes = obj.delayTimes === undefined ? state.delayTimes : obj.delayTimes
    state.expireDays = obj.expireDays === undefined ? state.expireDays : obj.expireDays
    state.regInfo = obj.regInfo === undefined ? state.regInfo : obj.regInfo
  },
  // 初始化容器
  [M.CONTAINER.INIT_CONTAINER] (state, payload) {
    let useSkin = skin[skin.useSkin]
    if (!useSkin.app.isRegister) {
      state.isRegisted = true
    } else {
      if (payload.isRegisted) {
        state.isRegisted = true
        state.serialNo = crypto.createHmac('sha1', 'TFSWX').update(state.machineCode.toString('hex')).digest('hex').toLocaleUpperCase()
      } else {
        if (!useSkin.app.isTrial) {
          state.isRegisted = false
          state.usedDays = 0
        } else {
          state.usedDays = parseInt(payload.sub) >= 0 ? parseInt(state.expireDays) - parseInt(payload.sub) : 0
        }
      }
    }
  },
  // 机器码
  [M.CONTAINER.GET_MACHINE_CODE] (state, payload) {
    state.machineCode = payload.code
  },
  [mutation.container.setSerialNo] (state, serialNo) {
    state.serialNo = serialNo
  },
  [mutation.container.setSync] (state, value) {
    state.isSync = value
    localStorage.setItem('syncAuthorization', value)
  }
}

const actions = {
  /**
   * 初始化容器配置
   */
  async [A.CONTAINER.initSetting] (ctx, data) {
    let useSkin = skin[skin.useSkin]

    // 使用默认配置
    let expireDays = useSkin.app.expireDays
    let delayTimes = useSkin.app.delayTimes

    let regInfo = L.LocalStore.getRegInfo()
    let tyywIp = localStorage.getItem('tyywIP')
    let isSync = localStorage.getItem('syncAuthorization')
    isSync = isSync === 'false' ? false : true

    // 使用服务端配置
    if (!regInfo) {
      regInfo = {
        regDate: '',
        fstartupdate: moment().format('YYYY-MM-DD HH:mm:ss'),
        usedTimes: 0
      }
    } else {
      if (regInfo.expireDays) expireDays = regInfo.expireDays
      if (regInfo.delayTimes) delayTimes = regInfo.delayTimes
    }

    let isRegisted = regInfo && regInfo.regDate

    if (!isRegisted && tyywIp && isSync) {
      try {
        let res = await axios.post(`http://${tyywIp}/ClientFile/getAuthorization`)

        if (res.status === 200) {
          res = res.data
          expireDays = res.expireDays
          delayTimes = res.delayTimes
          if (regInfo.isSever) {
            regInfo.regDate = res.regDate
            regInfo.expireDays = res.expireDays
            regInfo.delayTimes = res.delayTimes
          } else {
            regInfo = res
          }
          isRegisted = regInfo && regInfo.regDate
        }
      } catch (e) {
        console.error(e)
      }
    }
    ctx.commit(M.CONTAINER.initSetting, {isRegisted, regInfo, isSync, expireDays, delayTimes})
    regInfo.lstartupdate = moment().format('YYYY-MM-DD HH:mm:ss')
    return regInfo
  },

  /**
   * 初始化容器
   */
  async [A.CONTAINER.initContainer] (ctx, data) {
    let useSkin = skin[skin.useSkin]
    let regInfo = await ctx.dispatch(A.CONTAINER.initSetting)

    ctx.dispatch(A.CONTAINER.getMachineCode)
    let sub = 0
    // let flag = false
    // regInfo.lstartupdate = moment().format('YYYY-MM-DD HH:mm:ss')
    let ldate = (new Date(regInfo.fstartupdate)).getTime()
    let now = (new Date()).getTime()
    sub = parseInt((now - ldate) / (1000 * 60 * 60 * 24))
    // flag = regInfo.regDate !== ''

    if (useSkin.app.isTrial && !ctx.state.isRegisted && sub >= ctx.state.expireDays) {
      regInfo.usedTimes = regInfo.usedTimes ? regInfo.usedTimes : 0
      if (ctx.state.delayTimes && regInfo.usedTimes < ctx.state.delayTimes) {
        ctx.state.isExtensionUse = true
        try {
          await this._vm.$confirm('当前试用已到期，是否继续试用', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning'
          })
          regInfo.fstartupdate = moment().format('YYYY-MM-DD HH:mm:ss')
          regInfo.lstartupdate = moment().format('YYYY-MM-DD HH:mm:ss')
          regInfo.usedTimes = regInfo.usedTimes ? regInfo.usedTimes + 1 : 1
          sub = 0

          ctx.state.isExtensionUse = false
        } catch (e) {

        }
      }
    }

    L.LocalStore.setRegInfo(regInfo)
    ctx.commit(M.CONTAINER.INIT_CONTAINER, {isRegisted: ctx.state.isRegisted, sub: sub})

    // let setupInfo = L.LocalStore.getSetupInfo()
    // debugger
    // if (setupInfo) {
    //   ctx.commit(M.CONTAINER.GET_SETUP_INFO, setupInfo)
    // }
  },

  /**
   * 获取机器码
   */
  [A.CONTAINER.getMachineCode] (ctx) {
    process.exec('wmic cpu get processorid', function (error, stdout) {
      if (error) {
        console.log(error)
      } else {
        let machineCode = L.LocalStore.getMachineCode()
        if (!machineCode) {
          let code = stdout.replace(/\n/g, '').replace(/\r/g, '').replace(/ /g, '').replace('ProcessorId', '')
          let keyArr = Buffer.from(code).toString('hex').split('')
          let hexadecimal = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
          let indexArr = [2, 7, 10, 13, 15, 16, 21, 31]
          for (let i = indexArr.length - 1; i >= 0; i--) {
            // 获取随机数
            let str = hexadecimal[Math.floor(Math.random() * 16)]
            // 插入位置
            let index = indexArr[i] >= keyArr.length ? keyArr.length : indexArr[i]
            keyArr.splice(index, 0, str)
          }
          machineCode = keyArr.join('')
          L.LocalStore.setMachineCode(machineCode)
        }
        ctx.commit(M.CONTAINER.GET_MACHINE_CODE, {code: machineCode})
      }
    })
  },

  // /**
  //  * 服务器配置信息Ip
  //  */
  // [A.CONTAINER.saveSetupInfo](ctx, data) {
  //   L.LocalStore.setSetupInfo(data);
  //   ctx.commit(M.CONTAINER.GET_SETUP_INFO, data)
  // },

  /**
   * 获取序列号
   */
  [action.container.setSerialNo] ({commit}, serialNo) {
    commit(mutation.container.setSerialNo, serialNo)
  },
  [action.container.setSync] ({commit}, value) {
    commit(mutation.container.setSync, value)
  }

}

export default {
  state,
  mutations,
  actions
}
